Page({
  data: {
    userInfo: {},
    currentDate: '',
    todayCourses: [],
    todoList: []
  },

  onLoad() {
    this.setCurrentDate()
    this.getUserInfo()
    this.fetchTodayCourses()
    this.fetchTodoList()
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.fetchTodayCourses()
    this.fetchTodoList()
  },
  
  // 设置当前日期
  setCurrentDate() {
    const now = new Date()
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const date = `${now.getMonth() + 1}月${now.getDate()}日 ${weekdays[now.getDay()]}`
    this.setData({ currentDate: date })
  },

  // 获取用户信息
  async getUserInfo() {
    try {
      const userInfo = wx.getStorageSync('userInfo')
      if (userInfo) {
        this.setData({ userInfo })
      }
    } catch (err) {
      console.error('获取用户信息失败', err)
    }
  },

  // 获取今日课程
  async fetchTodayCourses() {
    try {
      const db = wx.cloud.database()
      const today = new Date()
      const weekday = today.getDay() || 7 // 转换为 1-7

      const res = await db.collection('courses')
        .where({
          teacherId: wx.getStorageSync('teacherId'),
          weekday: weekday
        })
        .orderBy('startTime', 'asc')
        .get()

      // 处理课程状态
      const courses = res.data.map(course => {
        return {
          ...course,
          status: this.getCourseStatus(course.startTime, course.endTime),
          statusText: this.getStatusText(this.getCourseStatus(course.startTime, course.endTime))
        }
      })

      this.setData({ todayCourses: courses })
    } catch (err) {
      console.error('获取今日课程失败', err)
      wx.showToast({
        title: '获取课程信息失败',
        icon: 'none'
      })
    }
  },

  // 获取待办事项
  async fetchTodoList() {
    try {
      const db = wx.cloud.database()
      const today = new Date()
      today.setHours(0, 0, 0, 0)

      const res = await db.collection('todos')
        .where({
          teacherId: wx.getStorageSync('teacherId'),
          date: db.command.gte(today)
        })
        .orderBy('date', 'asc')
        .limit(5)
        .get()

      this.setData({ todoList: res.data })
    } catch (err) {
      console.error('获取待办事项失败', err)
    }
  },

  // 获取课程状态
  getCourseStatus(startTime, endTime) {
    const now = new Date()
    const currentTime = now.getHours() * 60 + now.getMinutes()
    const [startHour, startMinute] = startTime.split(':')
    const [endHour, endMinute] = endTime.split(':')
    const startMinutes = parseInt(startHour) * 60 + parseInt(startMinute)
    const endMinutes = parseInt(endHour) * 60 + parseInt(endMinute)

    if (currentTime < startMinutes) return 'upcoming'
    if (currentTime > endMinutes) return 'finished'
    return 'ongoing'
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      upcoming: '即将开始',
      ongoing: '进行中',
      finished: '已结束'
    }
    return statusMap[status]
  },

  // 页面导航
  navigateTo(e) {
    console.info('e',e.currentTarget.dataset)
    const { path } = e.currentTarget.dataset
    wx.navigateTo({ url: path })
  },

  navigateToSchedule(){
    console.log('navigateTo....ing');
    // wx.navigateTo({ url: '/pages/schedule/schedule' });
    wx.switchTab({url:'/pages/schedule/schedule'})
  }
})